package k8sutil

import (
	"context"
	"fmt"
	"time"

	"github.com/pkg/errors"

	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	k8stypes "k8s.io/apimachinery/pkg/types"
	"k8s.io/client-go/kubernetes"
	bootstrapapi "k8s.io/cluster-bootstrap/token/api"
	bootstraputil "k8s.io/cluster-bootstrap/token/util"
	kbclient "sigs.k8s.io/controller-runtime/pkg/client"
)

// GenerateBootstrapToken will generate a node join token for kubeadm.
// ttl defines the time to live for this token.
func GenerateBootstrapToken(client kubernetes.Interface, ttl time.Duration) (string, error) {
	data := map[string][]byte{}
	data[bootstrapapi.BootstrapTokenDescriptionKey] = []byte("Token auto generated by Kotsadm.")
	for _, usage := range []string{"authentication", "signing"} {
		data[bootstrapapi.BootstrapTokenUsagePrefix+usage] = []byte("true")
	}
	data[bootstrapapi.BootstrapTokenExtraGroupsKey] = []byte("system:bootstrappers:kubeadm:default-node-token")

	token, secret, err := generateJoinToken(ttl, data)
	if err != nil {
		return "", errors.Wrap(err, "failed to generate join token")
	}
	if _, err := client.CoreV1().Secrets(metav1.NamespaceSystem).Create(context.TODO(), secret, metav1.CreateOptions{}); err != nil {
		return "", errors.Wrapf(err, "failed to create bootstrap token secret with name %s", secret.ObjectMeta.Name)
	}
	return token, nil
}

func GenerateK0sBootstrapToken(client kbclient.Client, ttl time.Duration, role string) (string, error) {
	data := make(map[string][]byte)

	// these 'data' entries are taken from k0s: https://github.com/replicatedhq/k0s/blob/7bc57553ea8ccb6847fdd8249701554ee8be1ab0/pkg/token/manager.go#L69
	data["usage-bootstrap-api-auth"] = []byte("true")
	if role == "worker" {
		data["description"] = []byte("Worker bootstrap token generated by Kotsadm for k0s")
		data["usage-bootstrap-authentication"] = []byte("true")
		data["usage-bootstrap-api-worker-calls"] = []byte("true")
	} else {
		data["description"] = []byte("Controller bootstrap token generated by Kotsadm for k0s")
		data["usage-bootstrap-authentication"] = []byte("false")
		data["usage-bootstrap-signing"] = []byte("false")
		data["usage-controller-join"] = []byte("true")
	}

	token, secret, err := generateJoinToken(ttl, data)
	if err != nil {
		return "", errors.Wrap(err, "failed to generate join token")
	}
	if err := client.Create(context.TODO(), secret); err != nil {
		return "", errors.Wrapf(err, "failed to create bootstrap token secret with name %s", secret.ObjectMeta.Name)
	}
	return token, nil
}

func generateJoinToken(ttl time.Duration, data map[string][]byte) (string, *corev1.Secret, error) {
	token, err := bootstraputil.GenerateBootstrapToken()
	if err != nil {
		return "", nil, errors.Wrap(err, "generate bootstrap token")
	}
	substrs := bootstraputil.BootstrapTokenRegexp.FindStringSubmatch(token)
	tokenID := substrs[1]
	tokenSecret := substrs[2]

	data[bootstrapapi.BootstrapTokenIDKey] = []byte(tokenID)
	data[bootstrapapi.BootstrapTokenSecretKey] = []byte(tokenSecret)

	expirationString := time.Now().Add(ttl).UTC().Format(time.RFC3339)
	data[bootstrapapi.BootstrapTokenExpirationKey] = []byte(expirationString)

	secretName := fmt.Sprintf("%s%s", bootstrapapi.BootstrapTokenSecretPrefix, tokenID)
	secret := &corev1.Secret{
		ObjectMeta: metav1.ObjectMeta{
			Name:      secretName,
			Namespace: metav1.NamespaceSystem,
		},
		Type: bootstrapapi.SecretTypeBootstrapToken,
		Data: data,
	}

	return token, secret, nil
}

func GetClusterCaCert(ctx context.Context, client kbclient.Client) (string, error) {
	var cert corev1.ConfigMap
	if err := client.Get(ctx, k8stypes.NamespacedName{Name: "kube-root-ca.crt", Namespace: "kube-system"}, &cert); err != nil {
		return "", errors.Wrap(err, "failed to get kube-root-ca.crt")
	}

	caCert, ok := cert.Data["ca.crt"]
	if !ok {
		return "", fmt.Errorf("ca.crt not found in kube-root-ca.crt, actual data was %v", cert.Data)
	}

	return caCert, nil
}
